<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Title</title>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <style>
      * {
        margin: 0px;
        padding: 0px;
      }
      .table-hover > tbody > tr:hover {
        color: skyblue;
      }
    </style>
  </head>
  <body>
    <div class="container-fluid p-0">
      <table class="table table-bordered table-hover text-center">
        <thead>
          <tr class="table-info"></tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script>
      $(function () {
        getData();
      });
      function getData() {
        $.ajax({
          type: "get",
          url: "/table",
          dataType: "json",
          success: function (response) {
            for (let index = 0; index < response.length; index++) {
              if (response[index]["出生日期"] == null) {
                response[index]["出生日期"] = "未填写";
              } else {
                response[index]["出生日期"] = new Date(
                  response[index]["出生日期"]
                ).toLocaleDateString();
              }
            }
            initTable(response);
          },
          error: function (err) {
            console.log(err);
          },
        });
      }
      function initTable(arr) {
        $(".table-info").html("");
        $("tbody").html("");
        for (const item in arr[0]) {
          $(".table-info").append(`<th>${item}</th>`);
        }
        $(".table-info").append(`<th>操作</th>`);
        arr.forEach((item, index) => {
          $("tbody").append(`
              <tr>
                <td>${item["姓名"]}</td>
                <td>${item["年龄"]}</td>
                <td>${item["性别"]}</td>
                <td>${item["学号"]}</td>
                <td>${item["出生日期"]}</td>
                <td>
                  <button class="btn btn-primary" type="button" onclick="delStud(${item["学号"]})">删除</button>
                  <button class="btn btn-primary" type="button">修改</button>
                </td>
              </tr>
            `);
        });
      }
      function delStud(stuId) {
        $.ajax({
          type: "get",
          url: `/table/delStud?stuId=${stuId}`,
          success: function (response) {
            let flag = Boolean(response);
            if (flag) {
              getData();
            } else {
              //调用弹框告诉删除失败
              console.log("删除失败");
            }
          },
        });
      }
    </script>
  </body>
</html>
